package com.sugon.controller.device;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.DataFilter;
import com.sugon.annotation.NonBusinessParamValid;
import com.sugon.entity.DevMaintenPlanEntity;
import com.sugon.modules.base.model.vo.BaseApproveParamVO;
import com.sugon.modules.base.model.vo.ProcessProgressConst;
import com.sugon.modules.device.model.entity.DevMaintenancePlanEntity;
import com.sugon.modules.device.model.vo.DevMaintenanceRuleParamVO;
import com.sugon.modules.device.service.IDeviceMaintenanceManager;
import com.sugon.modules.device.service.IDeviceMaintenanceRuleManager;
import com.sugon.service.DevMaintenPlanService;
import com.sugon.service.DevMaintenancePlanService;
import com.sugon.service.SysConfigService;
import com.sugon.utils.PageUtils;
import com.sugon.utils.Query;
import com.sugon.utils.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;

/**
 * 设备预防维护规程管理Controller
 *
 * @author YuXD
 * @date 2023-03-15
 */
@Controller
@RequestMapping("devmaintenplan")
public class DevPmRuleController {
    @Resource
    private DevMaintenPlanService devMaintenPlanService;
    @Resource
    private DevMaintenancePlanService devMaintenancePlanService;
    @Resource
    private IDeviceMaintenanceManager deviceMaintenanceManager;
    @Resource
    private IDeviceMaintenanceRuleManager deviceMaintenanceRuleManager;
    @Resource
    private SysConfigService configService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("devmaintenplan:list")
    @ResponseBody
    @DataFilter(deptAlias = "DEPT_CODE", userAlias = "ORG_USER_ID")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<DevMaintenPlanEntity> devMaintenPlanList = devMaintenPlanService.queryList(query);
        int total = devMaintenPlanService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(devMaintenPlanList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
//    @RequiresPermissions("devmaintenplan:info")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        DevMaintenPlanEntity devMaintenPlan = devMaintenPlanService.queryObject(id);

        return R.ok().put("devMaintenPlan", devMaintenPlan);
    }

    /**
     * 保存
     */
    @NonBusinessParamValid
    @RequestMapping("/save")
    @RequiresPermissions("devmaintenplan:save")
    @ResponseBody
    public R save(@Validated @RequestBody DevMaintenanceRuleParamVO devMaintenPlan, BindingResult bindingResult) {
        return deviceMaintenanceManager.addDeviceMaintenanceRule(devMaintenPlan) ? R.ok() : R.error();
    }

    /**
     * 修改
     */
    @AutoLog("维护规程修改")
    @RequestMapping("/update")
    @RequiresPermissions("devmaintenplan:update")
    @ResponseBody
    public R update(@RequestBody DevMaintenPlanEntity devMaintenPlan) {
        devMaintenPlanService.update(devMaintenPlan);

        return R.ok();
    }

    /**
     * 车间设备技术室主管审核
     */
    @NonBusinessParamValid
    @AutoLog("维护规程--车间审核")
    @RequestMapping("/check")
    @RequiresPermissions("devmaintenplan:check")
    @ResponseBody
    public R check(@Validated @RequestBody BaseApproveParamVO approveParam, BindingResult bindingResult) {
        return deviceMaintenanceRuleManager.workshopBatchApprove(approveParam) ? R.ok() : R.error();
    }

    /**
     * PE审核
     */
    @NonBusinessParamValid
    @AutoLog("维护规程--PE审核")
    @RequestMapping("/okCheck")
    @RequiresPermissions("devmaintenplan:okCheck")
    @ResponseBody
    public R okCheck(@Validated @RequestBody BaseApproveParamVO approveParam, BindingResult bindingResult) {
        return deviceMaintenanceRuleManager.peBatchApprove(approveParam) ? R.ok() : R.error();
    }

    /**
     * 删除- 逻辑
     */
    @AutoLog("维护规程逻辑删除")
    @RequestMapping("/updateDel")
    @RequiresPermissions("devmaintenplan:delete")
    @ResponseBody
    public R updateDel(@RequestBody DevMaintenPlanEntity devMaintenPlan) {
        devMaintenPlanService.update(devMaintenPlan);

        return R.ok();
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("devmaintenplan:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        devMaintenPlanService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<DevMaintenPlanEntity> list = devMaintenPlanService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 罗列出当前车间产线下已审核通过的且未添加的设备规程列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/listByEnd")
    @ResponseBody
    @DataFilter(deptAlias = "DI.DEPT_CODE", userAlias = "ORG_USER_ID")
    public R listByEnd(@RequestParam Map<String, Object> params) {
        // 检查参数中是否含有计划ID,如果有找到设备
        String planId = MapUtil.getStr(params, "planId");
        if (StrUtil.isEmpty(planId)) {
            return R.error("设备维护计划必选！");
        }
        // 校验设备维护计划是否存在
        DevMaintenancePlanEntity devMaintenancePlan = devMaintenancePlanService.queryObject(planId);
        if (devMaintenancePlan == null) {
            return R.error("设备维护计划不存在，请确认！");
        }
        // 列出产线下已通过审核且有效的设备规程列表
        params.put("devLineId", devMaintenancePlan.getDevLineId());
        params.put("progress", ProcessProgressConst.PASSED);
        params.put("isValid", 1);
        Query query = new Query(params);
        List<DevMaintenPlanEntity> devMaintenPlanList = devMaintenPlanService.queryList(query);
        int total = devMaintenPlanService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(devMaintenPlanList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 导入Excel
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/imports")
    @RequiresPermissions("devmaintenplan:imports")
    @ResponseBody
    public R imports(@RequestParam("file") MultipartFile file) {
        return R.ok().put("err", devMaintenPlanService.imports2(file));
    }

    @AutoLog("设备维护规程--导出")
    @RequestMapping("/exportData")
    @RequiresPermissions("devmaintenplan:imports")
    public void export(@RequestParam Map<String, Object> params, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        // 移除空值参数
        com.sugon.utils.MapUtil.removeEmptyValue(params);
        TemplateExportParams templateExportParams = new TemplateExportParams(configService.getPoiTemplatePath() + "devMaintenanceDirectiveRulesTemplate.xlsx");
        modelMap.put(TemplateExcelConstants.FILE_NAME, "设备维护规程导出_" + com.sugon.modules.utils.DateUtil.today());
        modelMap.put(TemplateExcelConstants.PARAMS, templateExportParams);
        modelMap.put(TemplateExcelConstants.MAP_DATA, devMaintenPlanService.prepareExportData(params));
        PoiBaseView.render(modelMap, request, response, TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }

}
